#!/usr/bin/env bash
set -uo pipefail

#==============================================================#
# File      :   pg-grant-role
# Ctime     :   2020-12-16
# Mtime     :   2020-12-17
# Desc      :   grant role to postgres user
# Path      :   /pg/bin/pg-grant-role
# Depend    :   psql
# Author    :   Vonng(fengruohang@outlook.com)
# Copyright (C) 2018-2021 Ruohang Feng
#==============================================================#

PROG_NAME="$(basename $0))"
PROG_DIR="$(cd $(dirname $0) && pwd)"

#==============================================================#
#                             Usage                            #
#==============================================================#
function usage() {
	cat <<-'EOF'
		NAME
			pg-grant-role   -- grant role for target user

		SYNOPSIS
			pg-grant-role <username> [rolename,...]

		DESCRIPTION
			pg-grant-role will ADD roles to target user
			username could be a real user or role
			roles are comma separated role names

		EXAMPLES
			pg-grant-role   dbrole_readonly     dbrole_readwrite
			pg-grant-role   dbrole_readonly     replicator
			pg-grant-role   dbrole_readonly     dbuser_monitor
			pg-grant-role   dbrole_readwrite    dbrole_admin
			pg-grant-role   dbrole_admin        dbuser_admin


	EOF
	exit 1
}


#--------------------------------------------------------------#
# Name: pg-grant-role
# Arg1: user name
# ArgN: role name list
#--------------------------------------------------------------#
function pg-grant-role(){
	local user=${1}

	# join role list into comma separated quoted string
	shift
	if (( $# == 0 )); then
		echo "at least one role is needed"
		return 1
	fi
	local roles=""
	for role in "$@"
	do
		roles+="\"${role}\","
	done
	roles=$(echo ${roles} | sed 's/.$//')

	# build and execute grant sql cmd
	local sqlcmd="GRANT ${roles} TO \"${user}\";"
	echo ${sqlcmd}
	psql -AXtwq postgres -c "${sqlcmd}"
}


#==============================================================#
#                             Main                             #
#==============================================================#
if (( $# < 1 )); then
	usage
fi
case "$1" in
	-h | --help) usage ;;
esac

pg-grant-role "$@"